<template>
	<view class="pages">
		<plublic-navbar :is-back="true" :title="title" :background="background"></plublic-navbar>
		<view :style="'margin-top:'+top/2+'px;height:20rpx'"></view>
		<view class="infobox" v-if="isF">
			<view class="u-flex u-row-between u-p-l-50 u-p-r-40">
				<view class="left">
					<u--image :src="imgUrl+'common/nan.png'" width="165rpx" height="514rpx"
						mode="aspectFit"></u--image>
				</view>
				<view class="right">
					<view class="u-flex u-row-between u-border-bottom u-p-t-30 u-p-b-30">
						<text>年龄</text><text>{{getAge(info.birthday)}}岁</text>
					</view>
					<view class="u-flex u-row-between u-border-bottom u-p-t-30 u-p-b-30">
						<text>身高</text><text>{{info.height}}cm</text>
					</view>
					<view class="see" @click="goPlans">
						查看体重报告
					</view>
				</view>
			</view>
			<view class="table">
				<view class="tr u-flex u-flex-wrap u-row-between u-border-bottom">
					<view class="td u-border-right">
						<view class="u-flex u-row-between">
							<text>体重</text><text>{{info.weight}}kg</text>
						</view>
						<text class="date">{{$u.timeFormat(info.updateTime, 'yyyy/mm/dd hh:MM')}}</text>
					</view>
					<view class="td">
						<view class="u-flex u-row-between">
							<text>BMI</text><text>{{info.bmi}}%</text>
						</view>
						<text class="date">{{$u.timeFormat(info.updateTime, 'yyyy/mm/dd hh:MM')}}</text>
					</view>
				</view>
				<!-- <view class="tr u-flex u-flex-wrap u-row-between u-border-bottom">
					<view class="td u-border-right">
						<view class="u-flex u-row-between">
							<text>体脂率</text><text>70.5kg</text>
						</view>
					</view>
					<view class="td">
						<view class="u-flex u-row-between">
							<text>肌肉量</text><text>23</text>
						</view>
					</view>
				</view>
				<view class="tr u-flex u-flex-wrap u-row-between u-border-bottom">
					<view class="td u-border-right">
						<view class="u-flex u-row-between">
							<text>基础代谢</text><text>-</text>
						</view>
					</view>
					<view class="td">
						<view class="u-flex u-row-between">
							<text>健康评分</text><text>-</text>
						</view>
					</view>
				</view>
				<view class="tr u-flex u-flex-wrap u-row-between">
					<view class="td u-border-right">
						<view class="u-flex u-row-between">
							<text>体脂率</text><text>70.5kg</text>
						</view>
					</view>
					<view class="td">
						<view class="u-flex u-row-between">
							<text>肌肉量</text><text>23</text>
						</view>
					</view>
				</view> -->
			</view>

		</view>
		<view class="u-m-t-30" v-if="isF">
			<view class="mainbox">
				<view class="title u-flex u-row-between">
					<text class="name">体重趋势</text>
					<view class="u-flex pick" @click="show = true">
						<text>{{pickname}}</text><u-icon name="arrow-down-fill" size="14" color="#333333"></u-icon>
					</view>
				</view>
				<view class="box">
					    <qiun-data-charts 
						 ref="chart"
					      type="line"
					      :opts="opts"
						  :canvas2d='true'
						   canvasId='canvans2'
					      :chartData="chartData"
					    />
				</view>
				<view class="u-p-t-30 u-p-b-30 more" @click="goPage('/pages/service/trend')">
					查看更多趋势
				</view>
			</view>
		</view>
		<u-picker :show="show" :columns="columns" :closeOnClickOverlay="true" @cancel="cancel" @confirm="confirm" @close="close"></u-picker>
	</view>
</template>

<script>
	import {loginUrl} from '../../common/mixin.js';
		import {getTrendList,getBodyData} from '../../common/api.js';
	export default {
		mixins: [loginUrl],
		data() {
			return {
				baseUrl: uni.$u.http.config.baseURL,
				imgUrl:uni.$u.http.config.imgURl,
				background: '#ffffff',
				title: '体重记录',
				top: 0,
				sex: 0,
				show: false,
				type:1,
				info:{},
				rq: "",
				show4: false,
				isF:false,
				userinfo:uni.getStorageSync('userInfo'),
				columns: [
				    ['近7天', '近15天', '近30天', '近90天', '自定义']
				],
				pickname:'近7天',
				value4: "",
				      chartData: {},
				      //您可以通过修改 config-ucharts.js 文件中下标为 ['line'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				      opts: {
				        color: ["#1890FF","#91CB74","#FAC858","#25D59F","#73C0DE","#3CA272","#25D59F","#9A60B4","#ea7ccc"],
				        padding: [15,10,0,15],
				        dataLabel: true,
				        dataPointShape: true,
				        enableScroll: false,
						
				        legend: {
							 show: false,
						},
				        xAxis: {
				          disableGrid: false,
						  disabled: true,
						  axisLine: true,
						  axisLineColor: "#CCCCCC",
						  calibration: false,
						  fontColor: "#666666",
						  fontSize: 13,
						  lineHeight: 20,
						  marginTop: 0,
						  rotateLabel: false,
						  rotateAngle: 45,
						  itemCount: 5,
						  gridColor:"#bef2e3"
				        },
				        yAxis: {
				          gridType: "dash",
				          dashLength: 2,  
						   disabled:true,
						   gridColor:"#bef2e3",
				          data: [
				            {
				              min: 0,
				              max: 150
				            }
				          ]
				        },
				        extra: {
				          line: {
				            type: "curve",
				            width: 2,
				            activeType: "hollow",
				            linearType: "custom",
				            onShadow: true,
				            animation: "horizontal"
				          }
				        }
				      }
			}
		},
		  onReady() {
		    // this.getServerData();
		  },
		computed: {
		
			getAge() {
				 
				return (birthdayTimestamp) => {
						
					    // 将生日时间戳转换为Date对象
					    const birthDate = birthdayTimestamp;
					    // 获取当前时间
					    const currentDate = Number(new Date()); 
					    
					    // 计算两个日期之间的差异（以年为单位）uni.$u.timeFormat(this.timestamp, 'yyyy-mm-dd');
					    let age = uni.$u.timeFormat(currentDate, 'yyyy') - uni.$u.timeFormat(birthDate, 'yyyy');
					    // 检查是否还没到生日，如果是，则年龄减1
					    const monthDiff = uni.$u.timeFormat(currentDate, 'mm') -  uni.$u.timeFormat(birthDate, 'mm');
					    if (monthDiff < 0 || (monthDiff === 0 && uni.$u.timeFormat(currentDate, 'dd') < uni.$u.timeFormat(birthDate, 'dd'))) {
					        age--;
					    }
					    
					    return age;
					
					
				}
			},
		},
		onLoad() {
			let that = this
			
			uni.getStorage({
				key: 'top',
				success: function(res) {
					that.top = res.data;
					console.log(res.data);
				}
			});
		},
		onShow() {
			let that = this
			if(that.userinfo.height&&that.userinfo.weight){
				this.isF = true
			}else{
				this.$u.toast("请先完善资料");
				setTimeout(()=>{
						let uri = "/pages/member/user?pre=wp"
						that.goPage(uri)
				},800)
				return
			}
			let currentDate = new Date();
			currentDate.setHours(23, 59, 59, 0); // 设置为当天的开始时间
			that.enDate = uni.$u.date(currentDate, 'yyyy-mm-dd')
			let startDate = new Date(currentDate); // 复制当前日期对象
			startDate.setDate(currentDate.getDate() - 6); // 减去6天，得到7天前的开始时间（包括今天，所以是7天中的第一天）
			that.startDate = uni.$u.date(startDate, 'yyyy-mm-dd')
			that.getList()
			that.getBodyInfo()
			// this.updateChart()
		},
		
		methods: {
			updateChart() {
				console.log(this.$refs,'######3')
			      // if (this.$refs.chart) {
			      //   this.$refs.chart.update(); // 调用更新方法
			      // }
			    },
			goPlans(){
				let data = uni.getStorageSync('planData')
				if(data){
					let url = "/pages/service/plan"
					this.goPage(url)
					return
				}else{
					
					let url = "/pages/service/setgoals"
					this.goPage(url)
				}
				
			},
			goPage(e){
				if(this.isLogin(e)){
					this.globals.linkJump({
					  url:e,
					  callback: () => {
					    uni.setStorageSync('pagelist',e)
					  }
					});
					// uni.navigateTo({
					// 	url: e
					// })
				}
			
			},
			cancel() {
				this.show4 = false
				this.show = false
			},
			
			close() {
				this.show = false
				this.show4 = false
			},
					
			change() {
				this.show = true
			},
			// 时间选择
			confirm(e) {
				 console.log('confirm', e)
				 this.pickname = e.value[0]
				 
				 let currentDate = new Date();
				 currentDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间
				 this.enDate = uni.$u.date(currentDate, 'yyyy-mm-dd')
				 let startDate = new Date(currentDate); // 复制当前日期对象
				 // startDate.setDate(currentDate.getDate() - 30); // 减去6天，得到7天前的开始时间（包括今天，所以是7天中的第一天）
				 if(e.indexs[0] == 0){
					 startDate.setDate(currentDate.getDate() - 6);
				 }
				 if(e.indexs[0] == 1){
				 					 startDate.setDate(currentDate.getDate() - 15);
				 }
				 if(e.indexs[0] == 2){
				 					 startDate.setDate(currentDate.getDate() - 30);
				 }
				 if(e.indexs[0] == 3){
				 					 startDate.setDate(currentDate.getDate() - 90);
				 }
				  this.startDate = uni.$u.date(startDate, 'yyyy-mm-dd')
				 // console.log(uni.$u.date(currentDate, 'yyyy-mm-dd'),uni.$u.date(startDate, 'yyyy-mm-dd'),e.indexs[0])
				 this.getList()
				this.show = false
				// if(e.index[0] == 4){
					
				// }
			},
			async getBodyInfo(){
				let data={
					dataId:'',
					selectADate:'',
					compareDate:'',
					id:'',

				}
				await getBodyData({params: data}).then(res=>{
					this.info = res.bodyDataRespVO
				})
			},
			async getList() {
				let data = {
					dataId:this.id||'',
					type: this.type,
					startDate: this.startDate,
					enDate: this.enDate
				}
				await getTrendList({
					params: data
				}).then(res => {
					this.total_pages = Math.ceil(res.total / 10)
					
					// res.list.foreach(item=>{
						
					// })
					this.list = res
			
					
					let dates = []
					let numbers = []
					if(this.list.length){
						this.list.forEach(item=>{
							dates.push(item.date)
							numbers.push(item.value)
						})
					}
					
					// this.info.height=Math.max(...numbers)
					// this.info.low=Math.min(...numbers)
					// this.info.new = this.list[this.list.length - 1].value
					let that = this
					setTimeout(() => {
					  //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
					  let dataArr = {
					      categories: dates,
					      series: [
					       
					        {
					          name: " ",
					          linearColor: [
					            [
					              0,
					              "#25D59F"
					            ],
					            [
					              0.33,
					              "#25D59F"
					            ],
					            [
					              0.66,
					              "#25D59F"
					            ],
					            [
					              1,
					              "#25D59F"
					            ]
					          ],
					          setShadow: [
					            3,
					            8,
					            10,
					            "#cccccc"
					          ],
					          data: numbers
					        }
					      ]
					    };
						
					  that.chartData = JSON.parse(JSON.stringify(dataArr));
					}, 500);
					
					
					
				}).catch(err => {
			
				})
			},
			getServerData() {
			      //模拟从服务器获取数据时的延时
			      setTimeout(() => {
			        //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
			        let res = {
			            categories: ["2018","2019","2020","2021","2022","2023"],
			            series: [
			             
			              {
			                name: " ",
			                linearColor: [
			                  [
			                    0,
			                    "#25D59F"
			                  ],
			                  [
			                    0.33,
			                    "#25D59F"
			                  ],
			                  [
			                    0.66,
			                    "#25D59F"
			                  ],
			                  [
			                    1,
			                    "#25D59F"
			                  ]
			                ],
			                setShadow: [
			                  3,
			                  8,
			                  10,
			                  "#cccccc"
			                ],
			                data: [0,0,0,0,0,0]
			              }
			            ]
			          };
			        this.chartData = JSON.parse(JSON.stringify(res));
			      }, 500);
			    },
		}
	}
</script>

<style lang="scss">
	.pages {
		padding: 0 20rpx;
		background: #F5F5F5;
		box-sizing: border-box;
		height: 100vh;
	}

	.title {
		font-weight: 600;
		font-size: 36rpx;
		color: #333333;
		line-height: 1;
		text-align: center;
		font-style: normal;
		margin-bottom: 40rpx;
	}

	.tips {
		font-weight: 400;
		font-size: 24rpx;
		color: #666666;
		line-height: 33rpx;
		text-align: center;
		font-style: normal;
		padding: 0 40rpx;
	}
	.mainbox{
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		.title{
			font-weight: 600;
			font-size: 30rpx;
			color: #333333;
			line-height: 42rpx;
			text-align: left;
			font-style: normal;
		}
		.pick{
			height: 48rpx;
			border-radius: 24rpx;
			border: 1rpx solid #000000;
			padding: 0 20rpx;
			text{
				font-weight: 600;
				font-size: 24rpx;
				color: #333333;
				line-height: 48rpx;
				text-align: left;
				font-style: normal;
				margin-right: 10rpx;
			}
		}
		.more{
			font-weight: 600;
			font-size: 28rpx;
			color: #333333;
			line-height: 40rpx;
			text-align: center;
			font-style: normal;
		}
	}
	.infobox {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 20rpx;

		.left {
			width: 165rpx;

		}

		.right {
			width: calc(100% - 300rpx);
			font-weight: 600;
			font-size: 28rpx;
			color: #333333;
			text-align: left;
			font-style: normal;
		}

		.see {
			background: rgba(37, 213, 159, 0.1);
			border-radius: 10rpx;
			height: 88rpx;
			line-height: 88rpx;
			font-weight: 500;
			font-size: 26rpx;
			color: #25D59F;
			text-align: center;
			font-style: normal;
			margin-top: 30rpx;
			// padding: 0 30rpx;
		}

	}

	.table {
		.tr {
			.td {
				width: 50%;
				padding: 30rpx;

				text {
					font-weight: 600;
					font-size: 28rpx;
					color: #333333;
					font-style: normal;
				}

				.date {
					font-weight: 400;
					font-size: 20rpx;
					color: #999999;
					line-height: 28rpx;
					text-align: left;
					font-style: normal;
				}
			}
		}
	}
</style>